package com.hisense.hiioc.formtable.util;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Func {
	/**
	 * 将数据保留两位小数
	 */
	public static double getTwoDecimal(double num) {
		DecimalFormat dFormat = new DecimalFormat("#.00");
		String yearString = dFormat.format(num);
		Double temp = Double.valueOf(yearString);
		return temp;
	}

	/**
	 * 将一个list均分成n个list,主要通过偏移量来实现的
	 * @param source
	 * @return
	 */
	public static <T> List<List<T>> averageAssign(List<T> source,Integer n){
		List<List<T>> result = new ArrayList<List<T>>();
		Integer remaider = source.size()%n;  //(先计算出余数)
		Integer number = source.size()/n;  //然后是商
		Integer offset = 0;//偏移量
		for(Integer i = 0; i < n; i++){
			List<T> value = null;
			if( remaider > 0 ) {
				value = source.subList( i * number + offset, ( i + 1) * number + offset + 1);
				remaider--;
				offset++;
			}else{
				value = source.subList( i * number + offset, ( i + 1 ) * number + offset);
			}
			result.add(value);
		}
		return result;
	}

	/**
     *  利用java原生的摘要实现SHA256加密
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256StrJava(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
	
	/**
	 * 生成随机字符串
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();     
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }
	
	/**
	 * 取当前时间几分钟后的时间
	 * @param minute
	 * @return
	 */
	public static String getTimeByMinute(int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minute);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(calendar.getTime());

    }

	/**
	 * 取当前时间几分钟后的时间
	 * @param hours
	 * @return
	 */
	public static String getTimeByHours(int hours) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, hours);
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

	}
	
	/**
	 * 取当前时间几天后的时间
	 * @param
	 * @return
	 */
	public static String getTimeByDay(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, day);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(calendar.getTime());

    }
	/**
	 * 根据开始日期和天数计算结束日期
	 * @param startDate
	 * @param days
	 * @return
	 */
	public static String DateAddDay(String startDate,int days){
		String format = "yyyyMMdd";
		if (strstr(startDate, "-")){
			format = "yyyy-MM-dd";
		}
		String endDate = "";
		Date fDate=new Date();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);  
		    fDate = sdf.parse(startDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Calendar aCalendar = Calendar.getInstance();
		aCalendar.setTime(fDate);
		aCalendar.add(Calendar.DATE, days);
		SimpleDateFormat s=new SimpleDateFormat(format);
		endDate=s.format(aCalendar.getTime());
		return endDate;
	}


	/**
	 * 计算天数差
	 * @param Date1
	 * @param Date2
	 * @return
	 */
	public static int daysOfTwo(String Date1, String Date2) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");  
        Calendar cal = Calendar.getInstance();    
        try {
			cal.setTime(sdf.parse(Date1));
		} catch (ParseException e) {
			e.printStackTrace();
		}    
        long time1 = cal.getTimeInMillis();                 
        try {
			cal.setTime(sdf.parse(Date2));
		} catch (ParseException e) {
			e.printStackTrace();
		}    
        long time2 = cal.getTimeInMillis();         
        long between_days = (time1-time2)/(1000*3600*24) ;
        return Integer.parseInt(String.valueOf(between_days));
	}
	
	
	
	/**
	 * 根据格式获取几天后的时间
	 * @param startDate
	 * @param days
	 * @param format
	 * @return
	 */
	public static String DateAddDay(String startDate,int days,String format){
		String endDate = "";
		Date fDate=new Date();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);  
		    fDate = sdf.parse(startDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Calendar aCalendar = Calendar.getInstance();
		aCalendar.setTime(fDate);
		aCalendar.add(Calendar.DATE, days);
		SimpleDateFormat s=new SimpleDateFormat(format);
		endDate=s.format(aCalendar.getTime());
		return endDate;
	}
	
	/**
	 * 检查str2实在在str1中存在
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean strstr(String str1, String str2) {
		boolean jieguo;
		if (str1.indexOf(str2) != -1) {
			jieguo = true;
		} else {
			jieguo = false;
		}
		return jieguo;
	}

	
	/**
	 * 获取当前时间，参数为需要的格式，例如：yyyy-MM-dd HH:mm:ss
	 * @param fString 返回时间格式
	 * @return String 当前时间
	 */
	public static String getDatenow(String fString) {
		String now="";
		if (fString.equals(null) || fString.equals("")){
			fString="yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat df= new SimpleDateFormat(fString);
		Date nowDate = new Date();
		now =df.format(nowDate);
		return now;
	}
	
	/**
	 * 直接获取当前时间，格式为yyyy-MM-dd HH:mm:ss
	 * @return String 当前时间
	 */
	public static String getDatenow() {
		String now="";
		String fString="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat df= new SimpleDateFormat(fString);
		Date nowDate = new Date();
		now =df.format(nowDate);
		return now;
	}

	/**
	 * 返回随机指定位数的随机数(1-9)
	 * @param num 返回随机数的位数
	 * @return String 随机数
	 */
	public static String rand(int num) {
		Random r = new Random();
		String verify = "";
		for( int i=1 ; i<=num ; i++){
			verify += String.valueOf(r.nextInt(9) + 1);
		}
		return verify;
	}
	
	
	/**
     * 获取ip地址
     */
	public static String getMACAddress(String ip) {
		String str = "";
		String macAddress = "";
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC Address") > 1) {
						macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return macAddress;
	}
	
	/**
     * 
     */
    public static String getRemoteAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

    /**
     * 计算文件大小 流方式
     */
    
    public static long GetFileSizeByStream(String filePath){
        long fileSize=0l;
        FileChannel fc= null;  
        try {  
            File f= new File(filePath);  
            if (f.exists() && f.isFile()){  
                FileInputStream fis= new FileInputStream(f);  
                fc= fis.getChannel();  
                fileSize=fc.size()/1024;
                fis.close();
            }else{  
                //logger.info("file doesn't exist or is not a file");  
            }  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();
        } catch (IOException e) {  
        	e.printStackTrace();  
        } finally {  
            if (null!=fc){  
                try{  
                    fc.close(); 
                }catch(IOException e){  
                	e.printStackTrace();
                }  
            }   
        }
        return fileSize;
    }
    
    /**
     * 计算文件大小 io方式
     */
    public static int GetFileSizeByFile(String filePath) {
    	int fileSize=0;
        File f= new File(filePath);  
        if (f.exists() && f.isFile()){  
        	fileSize = (int)f.length()/1024;
        }
        return fileSize;
    }
    
    /**
     * 标准MD5加密方法
     * @param s
     * @return
     */
    public static String MD5_2(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

}
